package com.leyou.gateway.filter;

import com.leyou.common.constants.RedisConstants;
import com.leyou.common.constants.TokenConstants;
import com.leyou.common.entity.Payload;
import com.leyou.common.entity.UserInfo;
import com.leyou.common.utils.JwtUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.SignatureException;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <h3>leyou-project</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-06-07 10:39
 **/
@Component
@Slf4j
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private FilterProperties filterProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie cookie = cookies.getFirst(TokenConstants.COOKIE_NAME);
        try {

            if (cookie == null) {
                //结束
                throw new SignatureException( "未登录或状态无效");
            }
            String token = cookie.getValue();
            Payload<UserInfo> payload;
                payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);

            /**
             * 获取redis中的token,与这个token进行比较
             * 刷新token时间
             */
            UserInfo userInfo = payload.getUserInfo();
            if (userInfo == null) {
                throw new SignatureException( "未登录或状态无效");
            }
            String jti = redisTemplate.opsForValue().get(RedisConstants.JTI_KEY_PREFIX + userInfo.getId());
            if (!org.apache.commons.lang.StringUtils.equals(jti, payload.getId())) {
                throw new SignatureException("未登录或已经过期");
            }
            redisTemplate.expire(RedisConstants.JTI_KEY_PREFIX+userInfo.getId(), RedisConstants.TOKEN_EXPIRE_MINUTES, TimeUnit.MINUTES);
            log.info("用户{}正在访问资源{}", userInfo.getUsername(), request.getPath().toString());
            return chain.filter(exchange);
        } catch (ExpiredJwtException | SignatureException e ) {
            if (isAllowRequest(exchange)){
                return chain.filter(exchange);
            }
            log.error("用户非法访问资源{}", request.getPath().toString());
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        } catch (Exception e) {
            log.info("未知错误,可能是解析失败");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    private boolean isAllowRequest(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        String method = Objects.requireNonNull(request.getMethod()).toString();

        for (Map.Entry<String, Set<String>> entry : filterProperties.getAllowRequests().entrySet()) {
            String key = entry.getKey();
            Set<String> value = entry.getValue();
            if (StringUtils.startsWithIgnoreCase(path, key) && value.contains(method)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
